<?php

namespace Modules\Agent\Entities;

use Modules\Core\Entities\BaseEntity as Model;
use ThrowException;
use Setting; 
use DB;
use Asset;

class InviteRecord extends Model
{
    protected $guarded = [];
    protected $table = 'invite_records';
    static public $resourceName = '';

    protected $casts = [
        'base_reward' => 'json',
        'added_reward' => 'json',
        'node_reward' => 'json'
    ];

    public function user()
    {
        return $this->belongsTo('\Modules\User\Entities\User', 'user_id');
    }

    public function direct_inviter()
    {
        return $this->belongsTo('\Modules\User\Entities\User', 'direct_inviter_id');
    }

    public function indirect_inviter()
    {
        return $this->belongsTo('\Modules\User\Entities\User', 'indirect_inviter_id');
    }

    public function scopeSearch($query, $key)
    {
        return $query->whereHas('user', function ($query) use ($key) {
            return $query->where('name', 'like',  '%' . $key . '%')->orWhere('phone', $key);
        })->orWhereHas('direct_inviter', function ($query) use ($key) {
            return $query->where('name', 'like',  '%' . $key . '%')->orWhere('phone', $key);
        })->orWhereHas('indirect_inviter', function ($query) use ($key) {
            return $query->where('name', 'like',  '%' . $key . '%')->orWhere('phone', $key);
        });
    }

    // 发放邀请奖励
    public function sendReward()
    {
        $inviter  = $this->direct_inviter;

        $set = Setting::get('sys_invite') ?: [];
        $baseReward = @$set['base_reward'] ?: [];
        $addedReward = @$set['option_reward'] ?: [];

        DB::beginTransaction();

        // 计算应得的基础奖励
        $baseRewardRes = Asset::sendTo($baseReward, $inviter, [
            'description' => '邀请好友奖励',
            'type' =>  'invite_reward'
        ]);

        $addedRewardRes = null;

        // 计算额外奖励
        // 当前邀请人的下级数量 + 1 为当前邀请的序号
        $inviteIndex = $this->invite_index;
        foreach ($addedReward as $item) {
            // 邀请人数与设置的一致，则进行奖励
            $total = intVal($item['value']);

            // \Log::error($total);

            if ($inviteIndex  === $total) {

                $assetArray = @$item['asset'] ?: [];

                // 计算应得的额外基础奖励
                $addedRewardRes = Asset::sendTo($assetArray, $inviter, [
                    'description' => '邀请数达' . $total .  '个额外奖励',
                    'type' =>  'invite_added_reward'
                ]);
                
            }
        }

        $this->update([
            'base_reward' => $baseRewardRes,
            'added_reward' => $addedRewardRes,
            'status' => 1
        ]);

        DB::commit();

    }

    // 更新某节点内的邀请序号
    public function updateNodeInviteIndex()
    {
        $total = InviteRecord::where([
            'direct_inviter_id' => $this->direct_inviter_id,
            'invite_node_id' => $this->invite_node_id,
            ['id', '<', $this->id]
        ])->count();

        $this->update([
            'node_invite_index' => $total + 1
        ]);
    }

}
